package top.soyask.bbs.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import top.soyask.bbs.dao.IFansDao;
import top.soyask.bbs.domain.Fans;
import top.soyask.bbs.domain.User;
import top.soyask.db.operator.ObjectOperator;
import top.soyask.db.orm.criteria.Criteria;

public class FansDao implements IFansDao {

	private ObjectOperator operator = new ObjectOperator();


	@Override
	public List<User> nextFans(long uid, int page, int itemCount) {
		String sql = "select * from user join fans on " + "fans.fansId = user.uid where fans.uid = ? limit ?,?";
		int start = (page - 1) * itemCount;
		List<Map<String, Object>> result = operator.executeSQL(sql, uid, start, itemCount);
		List<User> users = new ArrayList<>();
		for (Map<String, Object> map : result) {
			User user = new User();
			user.setUid((long) map.get("uid"));
			user.setUname((String) map.get("uname"));
			user.setFans((int) map.get("fans"));
			user.setFollow((int) map.get("follow"));
			user.setInfo((String) map.get("info"));
			users.add(user);
		}
		return users;
	}

	@Override
	public List<User> nextFollow(long uid, int page, int itemCount) {
		String sql = "select * from user join fans on " + "fans.uid = user.uid where fans.fansId = ? limit ?,?";
		int start = (page - 1) * itemCount;
		List<Map<String, Object>> result = operator.executeSQL(sql, uid, start, itemCount);
		List<User> users = new ArrayList<>();
		for (Map<String, Object> map : result) {
			User user = new User();
			user.setUid((long) map.get("uid"));
			user.setUname((String) map.get("uname"));
			user.setFans((int) map.get("fans"));
			user.setFollow((int) map.get("follow"));
			user.setInfo((String) map.get("info"));
			users.add(user);
		}
		return users;
	}

	@Override
	public long fansCount(long uid) {
		Criteria criteria = new Criteria("uid",uid);
		long count = operator.count(Fans.class, criteria );
		return count;
	}
	
	@Override
	public long followCount(long uid) {
		Criteria criteria = new Criteria("fansId",uid);
		long count = operator.count(Fans.class, criteria );
		return count;
	}

	@Override
	public List<Long> followId(long uid) {
		String sql = "select uid from fans where fansId = ?";
		List<Map<String, Object>> result = operator.executeSQL(sql, uid);
		List<Long> follow = new ArrayList<>();
		for (Map<String, Object> map : result) {
			follow.add((Long) map.get("uid"));
		}
		return follow;
	}

	@Override
	public void follow(Fans fans, boolean follow) {
		if(follow){
			operator.save(fans);
		}else {
			Criteria c0 = new Criteria("uid", fans.getUid());
			Criteria c1 = new Criteria("fansId",fans.getFansId());
			operator.delete(Fans.class, c0,c1);
		}
	}
}
